import style from './index.module.scss'
import { Button, Space, Modal, Form, Input, InputNumber, Select, Radio, Upload, Table, message } from 'antd';
import React, { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import store from '../../../../store';
import { observer } from 'mobx-react'
const { Option } = Select;

//解构出子模块
const { Medal } = store;

const AddMedal = () => {
    const navigate = useNavigate();
    const [isContentOpen, setisContentOpen] = useState(false);//选择内容模态框
    const [isGoodsOpen, setisGoodsOpen] = useState(false);//选择商品模态框

    //存储图片文件上传地址
    const [img, setImg] = useState();
    // 存储上传后的图片的路径
    const [imgFile,setImgFile]=useState({})
    //上传图片
    const file = useRef(null)

    // ----------------------选择内容模态框------------
    const [content, setContent] = useState()

    const chooseContent = () => {
        console.log("选择内容");

        // 请求内容数据
        Medal.getAllContent(1)
        // 打开内容选择模态框
        setisContentOpen(true);
    }
    const contentOk = () => {
        // console.log("模态框确认");
        // console.log(Medal.selectContent);
        setContent(Medal.selectContent);
        setisContentOpen(false);
    };
    const contentCancel = () => {
        // console.log("取消");
        setisContentOpen(false);
    };

    const contentColumns = [
        {
            title: '内容名称',//表格列名
            dataIndex: 'name',//对应数据字段
            key: 'name',//该列的唯一值
        },
        {
            title: '所属App',
            dataIndex: 'app',
            key: 'app',
        },
        {
            title: '频道',
            dataIndex: 'channel',
            key: 'channel',
        },
    ]
    // ----------------------------选择内容模态框--条件查询表单
    const [contentQueryform] = Form.useForm();


    const contentFinish = (values) => {
        console.log('查询 ', values);
    };
    const contentQuery = () => {
        const a = contentQueryform.getFieldsValue(true)
        console.log(a)
        // 发起内容条件查询请求
        Medal.getQueryContent(a)
    };
    const contentClear = () => {
        contentQueryform.resetFields();
    };
    // ------------------------------选择商品模态框------------------
    const [goods, setGoods] = useState()
    const chooseGoods = () => {
        console.log("选择商品");
        Medal.getAllGoods(1)
        setisGoodsOpen(true);
    };
    const goodsOk = () => {
        // console.log("模态框确认");
        // console.log("选择的兑换商品", Medal.selectGoods)
        // console.log(Medal.selectGoods[0])
        setGoods(Medal.selectGoods)
        setisGoodsOpen(false);
    };
    const goodsCancel = () => {
        // console.log("取消");
        setisGoodsOpen(false);
    };

    const goodsColumns = [
        {
            title: '商品名称',//表格列名
            dataIndex: 'goodsName',//对应数据字段
            key: 'goodsName',//该列的唯一值
        },
        {
            title: '类目',
            dataIndex: 'categoryName',
            key: 'categoryName',
        },
    ]
    // ----------------------------选择商品模态框--条件查询表单
    const [goodsQueryform] = Form.useForm();
    const goodsFinish = (values) => {
        console.log('查询 ', values);
    };
    const goodsQuery = () => {
        const a = goodsQueryform.getFieldsValue(true)
        console.log(a)
        // 发起商品名称条件查询请求
        Medal.getQueryGoods(a)
    };
    const goodsClear = () => {
        goodsQueryform.resetFields();
    };

    //  ----------------------------------新增信息保存
    const onFinish = (values) => {
        //由于取消了内容、商品input框的name属性，所以需要在提交表单前重新赋值
        values.content = content;
        values.goods = goods;
        console.log('保存:', values);
        
        message.success('保存成功！')

        //发起图片上传请求
        Medal.addMedalImage(imgFile,values)
        setTimeout(() => {
            navigate(-1)
        }, 2000);
    };
    // ------------------------------新增信息不完善
    const onFinishFailed = () => {
        message.warning('请填写必要信息后保存!')
    };
    // ------------------------------取消新增
    const back = () => {
        navigate(-1);
    };
    //-------------------------上传头像handler
    const uploadFile = (e) => {
        const fileData = e.target.files[0];

        setImgFile(fileData)
        
        const pattern = /^image/;
        if (!pattern.test(fileData.type)) {
            message.error("图片格式不正确")
            return
        }
        const reader = new FileReader()
        reader.readAsDataURL(fileData)
        reader.onload = () => {
            setImg(reader.result)
        }
    }

    return <div className='addBox'>
        <h2>新增</h2>
        <Form name="addMedal"
            className={style.formStyle}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            initialValues={{ weight: 1000, status: "上架" }}
            labelCol={{ span: 4 }}>
            <Form.Item
                name="app"
                label="App"
                rules={[
                    {
                        required: true,
                        message: '请选择APP',
                    },
                ]}>
                <Radio.Group
                    optionType="button"
                    buttonStyle="solid">
                    <Radio.Button value="小黑早教">小黑早教</Radio.Button>
                    {/* <Radio.Button value="小黑绘本">小黑绘本</Radio.Button> */}
                </Radio.Group>
            </Form.Item>
            <Form.Item
                name="imgSrc"
                label="图标"
                rules={[{ required: true, message: '请选择头像' }]}
            >
                <div>
                    {(() => {
                        // console.log(img)
                        if (img) {
                            return <img
                                src={img}
                                alt="avatar"
                                style={{
                                    width: '60px',
                                    marginRight: '20px'
                                }} />
                        } else {
                            return ''
                        }
                    })()
                    }
                    <input ref={file} type="file" style={{ display: 'none' }} onChange={(e) => uploadFile(e)} />
                    <Button type={"primary"} onClick={() => {
                        file.current.click()
                    }
                    }>选择头像</Button>
                </div>
            </Form.Item>
            <Form.Item
                name="medalName"
                label="名称"
                rules={[{ required: true, message: '输入的勋章名称不合法', whitespace: true }]}
            >
                <Input className={style.inputStyle} />
            </Form.Item>
            <Form.Item noStyle >
                <Form.Item 
                   label="需完成内容"
                   rules={[{ required: true, message: '请选择内容', whitespace: true }]}>
                    <Input value={content} className={style.inputStyle} />
                   <Button style={{ marginLeft: "20px" }} onClick={chooseContent}>浏览</Button>
                </Form.Item>
            </Form.Item>
            <Form.Item
                name="points"
                label="可获积分"
                rules={[{
                    required: true,
                    message: '请输入积分',
                    pattern: new RegExp(/^(([1-9]\d*)|\d)$/, 'g'),
                }]}
            >
                <InputNumber className={style.inputStyle} />
            </Form.Item>
            <Form.Item noStyle>
                <Form.Item 
                    label="可兑换商品"
                    rules={[{ required: true, message: '请选择商品', whitespace: true }]}>
                    <Input value={goods} className={style.inputStyle} />
                    <Button style={{ marginLeft: "20px" }} onClick={chooseGoods}>浏览</Button>
                </Form.Item>

                

            </Form.Item>
            <Form.Item
                name="weight"
                label="权重"
                rules={[{
                    required: true,
                    message: '请输入权重',
                    pattern: new RegExp(/^(([1-9]\d*)|\d)$/, 'g'),
                }]}
            >
                <InputNumber className={style.inputStyle} placeholder='请输入正整数' />
            </Form.Item>
            <Form.Item
                name="status"
                label="状态"
                rules={[
                    {
                        required: true,
                        message: '请选择勋章的状态',
                    },
                ]}
            >
                <Radio.Group
                    optionType="button"
                    buttonStyle="solid">
                    <Radio.Button value="上架">上架</Radio.Button>
                    <Radio.Button value="下架">下架</Radio.Button>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                name="des"
                label="介绍"
                rules={[{ required: true, message: '请输入勋章介绍' }]}
            >
                <Input.TextArea showCount maxLength={200} className={style.inputStyle} />
            </Form.Item>


            <Space size={'large'} className={style.btnBox}>
                <Button type="primary" className={style.btnStyle} htmlType="submit">保存</Button>
                <Button className={style.btnStyle} onClick={back}>取消</Button>
            </Space>
        </Form>

        {/* --------------选择内容--------- */}
        <Modal title="选择内容"
            open={isContentOpen}
            onOk={contentOk}
            onCancel={contentCancel}
            okText="保存"
            cancelText="取消"
            width={650}>
            <Form
                form={contentQueryform}
                name='contentform'
                onFinish={contentFinish}
                layout="inline">
                {/* <Form.Item
                    label="所属App"
                    name="app"
                >
                    <Input placeholder='所属App' style={{ width: 100 }} />
                </Form.Item>
                <Form.Item
                    label="频道"
                    name="channel">
                    <Select style={{ width: 100 }}>
                        <Option value=''>全部</Option>
                        <Option value='国学'>国学</Option>
                        <Option value='英语'>英语</Option>
                        <Option value='逻辑'>逻辑</Option>
                        <Option value='美术'>美术</Option>
                    </Select>
                </Form.Item> */}
                <Form.Item
                    label="内容名称"
                    name="name">
                    <Input placeholder='内容名称' style={{ width: 100 }} />
                </Form.Item>

                <Space size={'large'}>
                    <Button type='primary' onClick={contentQuery} className='btnStyle'>搜索</Button>
                    <Button type='primary' onClick={contentClear} className='btnStyle'>重置</Button>
                </Space>

            </Form>
            <br />
            <Table
                rowSelection={{
                    type: 'checkbox',
                    onChange(selectedRowKeys, rows) {
                        //获取选中行的key值,多项选择时是一个数组
                        Medal.setSleContent(selectedRowKeys)
                        console.log(selectedRowKeys);
                    },
                    defaultSelectedRowKeys: [content]

                }}
                columns={contentColumns}
                dataSource={Medal.contentData}
                bordered
                pagination={false}
                rowKey={(record) => record.name}
                scroll={{
                    y: 240,
                }}
            />
        </Modal>
        {/* --------------选择商品--------- */}
        <Modal title="选择积分商品"
            open={isGoodsOpen}
            onOk={goodsOk}
            onCancel={goodsCancel}
            okText="保存"
            cancelText="取消"
        >
            <Form
                form={goodsQueryform}
                name='goodsform'
                onFinish={goodsFinish}
                layout="inline">
                {/* <Form.Item
                    label="类目"
                    name="categoryName">
                    <Select style={{ width: 100 }}>
                        <Option value=''>全部</Option>
                        <Option value='汽车'>汽车</Option>
                        <Option value='娃娃'>娃娃</Option>
                        <Option value='飞机'>飞机</Option>
                        <Option value='乐器'>乐器</Option>
                        <Option value='益智'>益智</Option>
                    </Select>
                </Form.Item> */}
                <Form.Item
                    label="商品名称"
                    name="goodsName">
                    <Input placeholder='商品名称' style={{ width: 100 }} />
                </Form.Item>

                <Space size={'large'}>
                    <Button type='primary' onClick={goodsQuery} className='btnStyle'>搜索</Button>
                    <Button type='primary' onClick={goodsClear} className='btnStyle'>重置</Button>
                </Space>

            </Form>
            <br />
            <Table
                rowSelection={{
                    type: 'checkbox',
                    onChange(selectedRowKeys, rows) {
                         //获取选中行的key值,多项选择时是一个数组
                        Medal.setSleGoods(selectedRowKeys)
                        console.log(rows,selectedRowKeys);
                    },
                    defaultSelectedRowKeys: [goods]
                }}
                columns={goodsColumns}
                dataSource={Medal.goodsData}
                bordered
                pagination={false}
                rowKey={(record) => record.goodsName}
                scroll={{
                    y: 240,
                }}
            />
        </Modal>
    </div>
}
export default observer(AddMedal);